﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Report;
using Kingdee.BOS.Core.SqlBuilder;
using Kingdee.BOS.Model.ReportFilter;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;

/// <summary>
/// 获取生产成本表单插件
/// </summary>
/// <remarks>
/// 功能：1、点击获取生产成本时，获取生产入库单成本价。更新到应收单中
/// 2024-8-6修改：获取存货收发存汇总表数据
/// 创建人：lxl
/// 创建日期：2024-5-16
/// 修改信息（1）：修改人，修改日期，修改内容
/// </remarks>
namespace LM.YF.K3Cloud.Plugin
{
    [HotUpdate, Description("获取生产成本表单插件")]
    public class GetProductBillPlugin : AbstractDynamicFormPlugIn
    {
        public override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            //获取年份
            int fyear = DateTime.Now.Year;
            int fmonth = DateTime.Now.Month;
            //string fType =Convert.ToString( this.View.OpenParameter.GetCustomParameter("FType"));
            this.Model.SetValue("F_QLTK_year", fyear);
            this.Model.SetValue("F_QLTK_month", fmonth);
        }

        public override void AfterButtonClick(AfterButtonClickEventArgs e)
        {
            base.AfterButtonClick(e);
            //点击获取数据后
            if (e.Key.ToUpper() == "F_QLTK_GETDATE")
            {
                string strSql;
                //获取选取的年月
                string fyear = Convert.ToString(this.Model.GetValue("F_QLTK_year"));
                string fmonth = Convert.ToString(this.Model.GetValue("F_QLTK_month"));
                bool F_QLTK_GETREV = Convert.ToBoolean(this.Model.GetValue("F_QLTK_GETREV"));//重新获取收发存数据
                if (F_QLTK_GETREV)
                {
                    strSql = $@" select FORGID,FNUMBER forgNumber from T_ORG_ORGANIZATIONS where FNUMBER 
                    not in ('1000')";
                    DynamicObjectCollection dtResult = DBUtils.ExecuteDynamicObject(this.Context, strSql);
                    foreach (DynamicObject item in dtResult)
                    {
                        string forgid = item["FORGID"].ToString();
                        string forgNumber = item["forgNumber"].ToString();
                        GetSql(forgid, forgNumber, fyear, fmonth);//获取存货收发存汇总表数据
                    }
                }

                strSql = $"exec dev_p_getProctCost {fyear},{fmonth}";
                int fresult = DBUtils.Execute(this.Context, strSql);
                if (fresult > 0)
                {
                    var result = new FormResult("sucess");
                    this.View.ReturnToParentWindow(result);
                    this.View.ShowMessage("更新成功");
                }
                else { this.View.ShowMessage("更新失败"); }
            }
        }

        /// <summary>
        /// 从系统标准报表“存货收发存汇总表中获取数据”
        /// </summary>
        /// <param name="forgId"></param>
        /// <param name="forgNumber"></param>
        /// <param name="YEAR"></param>
        /// <param name="MONTH"></param>
        /// <returns></returns>
        private DataTable GetSql(string forgId, string forgNumber, string YEAR, string MONTH)
        {
            #region 抓取收发存汇总表中的数据
            /*从成本计算单报表中读取数据*/

            ISysReportService sysReporSservice = ServiceFactory.GetSysReportService(this.Context);
            IPermissionService permissionService = ServiceFactory.GetPermissionService(this.Context);

            /*创建DataTable,用于获取从报表取出的数据*/
            DataTable dtResult = new DataTable();
            dtResult.Columns.Add("fyear", typeof(Int32));//年
            dtResult.Columns.Add("fmonth", typeof(Int32));//月
            dtResult.Columns.Add("forgId", typeof(Int32));//组织id
            dtResult.Columns.Add("forgNumber", typeof(string));//组织编码
            dtResult.Columns.Add("FMATERIALBASEID", typeof(Int32));//记录物料内码
            dtResult.Columns.Add("FMATERIALID", typeof(string));//记录物料编码
            dtResult.Columns.Add("FUnitID", typeof(string));//单位内码
            dtResult.Columns.Add("FSTOCKID", typeof(string));//仓库内码
            dtResult.Columns.Add("FINITQTY", typeof(string));//期初结存-数量
            dtResult.Columns.Add("FINITPRICE", typeof(string));//期初结存-单价
            dtResult.Columns.Add("FINITAMOUNT", typeof(double));//期初结存-金额
            dtResult.Columns.Add("FRECEIVEQTY", typeof(double)); //本期收入-数量
            dtResult.Columns.Add("FRECEIVEPRICE", typeof(string));//本期收入-单价
            dtResult.Columns.Add("FRECEIVEAMOUNT", typeof(string));//本期收入-金额
            dtResult.Columns.Add("FSENDQTY", typeof(double)); //本期发出-数量
            dtResult.Columns.Add("FSENDPRICE", typeof(string));//本期发出-单价
            dtResult.Columns.Add("FSENDAMOUNT", typeof(string));//本期发出-金额
            dtResult.Columns.Add("FENDQTY", typeof(string));//期末结存-数量
            dtResult.Columns.Add("FENDPRICE", typeof(string));//期末结存-单价
            dtResult.Columns.Add("FENDAMOUNT", typeof(string)); //期末结存-金额
            dtResult.Columns.Add("FPLANNO", typeof(string)); //计划跟踪号

            //加载字段比较元数据
            var filterMetadata = FormMetaDataCache.GetCachedFilterMetaData(this.Context);
            //报表元数据。
            var reportMetadata = FormMetaDataCache.GetCachedFormMetaData(this.Context, "HS_INOUTSTOCKSUMMARYRPT"); //收发存汇总表标识
                                                                                                                   //加载过滤条件元数据
            var reportFilterMetadata = FormMetaDataCache.GetCachedFormMetaData(this.Context, "HS_INOUTSTOCKSUMMARYFILTER");///收发存汇总表过滤条件标识
            var reportFilterServiceProvider = reportFilterMetadata.BusinessInfo.GetForm().GetFormServiceProvider();
            //创建报表过滤模型
            var model = new SysReportFilterModel();
            model.SetContext(this.Context, reportFilterMetadata.BusinessInfo, reportFilterServiceProvider);
            model.FormId = reportFilterMetadata.BusinessInfo.GetForm().Id;
            model.FilterObject.FilterMetaData = filterMetadata;
            model.InitFieldList(reportMetadata, reportFilterMetadata);
            model.GetSchemeList();

            //获取过滤方案，可以通过LoadScheme("Id")，查询报表默认存在的一些过滤方案
            //SELECT * FROM T_BAS_FILTERSCHEME where fschemename='应收获取工厂成本使用--勿删'
            //遍历所有的方案*每个组织都有一个方案，所以*
            string fschemeid = "66b2174f2641f5"; //过滤方案的ID
            var entity = model.Load(fschemeid);

            var filters = model.GetFilterParameter();
            DynamicObject orgObj = LoadBDObject("ORG_Organizations", forgNumber);//构建数据包
            filters.CustomFilter["ACCTGORGID"] = orgObj;
            filters.CustomFilter["ACCTGORGID_id"] = forgId;
            filters.CustomFilter["Year"] = YEAR;       //开始会计年度
            filters.CustomFilter["EndYear"] = YEAR;     //结束会计年度:取系统当前年份
            filters.CustomFilter["Period"] = MONTH;    //开始会计期间
            filters.CustomFilter["EndPeriod"] = MONTH;  //结束会计期间:取系统当前月份
            //外币核算
            if (forgNumber == "1025" || forgNumber == "1026" || forgNumber == "1027" || forgNumber == "1028" || forgNumber == "1029")
            {
                DynamicObject facctPolcyObj = LoadBDObject("BD_ACCTPOLICY", "KJZC01_DY");//涉外会计政策
                filters.CustomFilter["ACCTPOLICYID"] = facctPolcyObj;
                filters.CustomFilter["ACCTPOLICYID_id"] = 168113;
            }

            //报表参数
            IRptParams p = new RptParams();
            p.FormId = reportFilterMetadata.BusinessInfo.GetForm().Id;
            p.StartRow = 1; // StartRow和EndRow是报表数据分页的起始行数和截至行数，一般取所有数据，所以EndRow取int最大值
            p.EndRow = int.MaxValue;
            p.FilterParameter = filters;
            p.FilterFieldInfo = model.FilterFieldInfo;
            p.BaseDataTempTable.AddRange(permissionService.GetBaseDataTempTable(this.Context, reportMetadata.BusinessInfo.GetForm().Id));

            using (DataTable dt = sysReporSservice.GetData(this.Context, reportMetadata.BusinessInfo, p))
            {
                foreach (DataRow item in dt.Rows) //循环结果集
                {

                    if (item["FMATERIALID"].ToString().Contains("总计") == false)
                    {
                        DataRow drw = dtResult.NewRow();
                        drw["fyear"] = YEAR;
                        drw["fmonth"] = MONTH;
                        drw["forgId"] = forgId;
                        drw["forgNumber"] = forgNumber;
                        drw["FMATERIALBASEID"] = item["FMATERIALBASEID"];//物料内码
                        drw["FMATERIALID"] = item["FMATERIALID"]; //物料编码
                        drw["FUnitID"] = item["FUnitID"];//单位内码
                        drw["FSTOCKID"] = item["FSTOCKID"];//仓库内码
                        drw["FINITQTY"] = item["FINITQTY"];//期初结存-数量
                        drw["FINITPRICE"] = item["FINITPRICE"];//期初结存-单价
                        drw["FINITAMOUNT"] = item["FINITAMOUNT"];//期初结存-金额
                        drw["FRECEIVEQTY"] = item["FRECEIVEQTY"];//本期收入-数量
                        drw["FRECEIVEPRICE"] = item["FRECEIVEPRICE"];//本期收入-单价
                        drw["FRECEIVEAMOUNT"] = item["FRECEIVEAMOUNT"];//本期收入-金额
                        drw["FSENDQTY"] = item["FSENDQTY"];//本期发生-数量
                        drw["FSENDPRICE"] = item["FSENDPRICE"];//本期发生-单价
                        drw["FSENDAMOUNT"] = item["FSENDAMOUNT"];//本期发生-金额
                        drw["FENDQTY"] = item["FENDQTY"];//期末结存-数量
                        drw["FENDPRICE"] = item["FENDPRICE"];//期末结存-单价
                        drw["FENDAMOUNT"] = item["FENDAMOUNT"];//期末结存-金额
                        drw["FPLANNO"] = item["FPLANNO"];//期末结存-金额
                        dtResult.Rows.Add(drw);
                    }

                }
            }

            ServiceFactory.CloseService(sysReporSservice);
            ServiceFactory.CloseService(permissionService);
            //先删除数据再存入
            DBUtils.Execute(this.Context, $"delete from dev_t_revSedData where fyear={YEAR} and fmonth={MONTH} and forgId={forgId}");
            //将数据存到数据表临时表中
            string connectionString = "Data Source=10.10.11.101;database=AIS20240514124535;Uid=sa;Pwd=123qwe!@#;";
            SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction);
            sqlbulkcopy.DestinationTableName = "dev_t_revSedData";//数据库中的自己创建表名
            sqlbulkcopy.WriteToServer(dtResult);
            #endregion

            //string strsql = "select * from " + tempTableName;
            DataTable dt1 = dtResult;
            return dt1;

        }

        /// 构造基础资料
        /// </summary>
        /// <param name="myFilter"></param>
        private DynamicObject LoadBDObject(string formId, string number)
        {
            FormMetadata meta = MetaDataServiceHelper.Load(this.Context, formId) as FormMetadata;
            // 构建查询参数，设置过滤条件    
            QueryBuilderParemeter queryParam = new QueryBuilderParemeter();
            queryParam.FormId = formId;
            queryParam.BusinessInfo = meta.BusinessInfo;
            queryParam.FilterClauseWihtKey = string.Format(" {0} = '{1}' ", meta.BusinessInfo.GetForm().NumberFieldKey, number);
            var bdObjs = BusinessDataServiceHelper.Load(this.Context, meta.BusinessInfo.GetDynamicObjectType(), queryParam);
            return bdObjs[0];
        }

    }
}
